import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../../models/community_post.dart';
import '../../providers/community_provider.dart';

class CommunityPage extends StatefulWidget {
  const CommunityPage({super.key});

  @override 
  State<CommunityPage> createState() => _CommunityPageState();
}

class _CommunityPageState extends State<CommunityPage> {
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  // ignore: unused_field
  List<CommunityPost> _posts = [];
  List<CommunityPost> _filteredPosts = [];
  bool _isLoading = true;
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadPosts();
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  void _loadPosts() {
    final provider = Provider.of<CommunityProvider>(context, listen: false);
    provider.loadPosts(refresh: true);
  }

  void _onScroll() {
    if (_scrollController.position.pixels >= 
        _scrollController.position.maxScrollExtent - 200) {
      final provider = Provider.of<CommunityProvider>(context, listen: false);
      if (!provider.isLoading && provider.hasMore) {
        provider.loadPosts();
      }
    }
  }


  void _onSearch(String query) {
    setState(() {
      _searchQuery = query;
    });
    final provider = Provider.of<CommunityProvider>(context, listen: false);
    provider.loadPosts(
      refresh: true,
      title: query.isNotEmpty ? query : null,
    );
  }

  void _toggleLike(CommunityPost post) {
    final provider = Provider.of<CommunityProvider>(context, listen: false);
    provider.toggleLikePost(post.id);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true, // 推荐开启
      backgroundColor: Colors.grey[50],
      body: CustomScrollView(
        controller: _scrollController,
        physics: const BouncingScrollPhysics(),
        slivers: [
          // Custom AppBar
          _buildSliverAppBar(),
          
          // Waterfall Grid Content
          Consumer<CommunityProvider>(
            builder: (context, provider, child) {
              _posts = provider.posts;
              _filteredPosts = provider.posts;
              _isLoading = provider.isLoading && provider.posts.isEmpty;
              
              return SliverToBoxAdapter(
                child: SizedBox(
                  height: MediaQuery.of(context).size.height - 120,
                  child: _isLoading ? _buildLoadingWidget() : _buildWaterfallGrid(provider),
                ),
              );
            },
          ),
        ],
      ),
      // Publish Button
      floatingActionButton: Container(
        margin: const EdgeInsets.only(bottom: 80), // 靠上一些，避免被底部导航栏遮挡
        child: FloatingActionButton(
          onPressed: () {
            context.push('/community/create');
          },
          backgroundColor: Colors.blue[600],
          child: const Icon(
            Icons.add,
            color: Colors.white,
            size: 28,
          ),
        ),
      ),
    );
  }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
      floating: false,
      pinned: true,
      snap: false,
      stretch: false,
      backgroundColor: Colors.blue[600],
      flexibleSpace: FlexibleSpaceBar(
        title: const Text(
          '钓友圈',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
        background: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.blue[600]!,
                Colors.blue[800]!,
              ],
            ),
          ),
        ),
      ),
      actions: [
        IconButton(
          icon: const Icon(Icons.search, color: Colors.white),
          onPressed: _showSearchDialog,
        ),
      ],
    );
  }

  Widget _buildLoadingWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text(
            '正在加载...',
            style: TextStyle(color: Colors.grey),
          ),
        ],
      ),
    );
  }

  Widget _buildWaterfallGrid(CommunityProvider provider) {
    if (_filteredPosts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.search_off,
              size: 80,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              _searchQuery.isEmpty ? '暂无内容' : '未找到相关内容',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () => _onRefresh(provider),
      child: Column(
        children: [
          Expanded(
            child: MasonryGridView.count(
              crossAxisCount: 2,
              mainAxisSpacing: 8,
              crossAxisSpacing: 8,
              padding: const EdgeInsets.all(16),
              itemCount: _filteredPosts.length,
              itemBuilder: (context, index) {
                return _buildPostCard(_filteredPosts[index]);
              },
            ),
          ),
          if (provider.isLoading && provider.posts.isNotEmpty)
            const Padding(
              padding: EdgeInsets.all(16.0),
              child: CircularProgressIndicator(),
            ),
        ],
      ),
    );
  }

  Widget _buildPostCard(CommunityPost post) {
    return GestureDetector(
      onTap: () {
        context.push('/community/${post.id}', extra: post);
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withAlpha((0.05 * 255).round()),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          // Images
          if (post.images.isNotEmpty) _buildPostImages(post),
          
          // Content
          Padding(
            padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // Title
                Text(
                  post.title,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                
                const SizedBox(height: 6),
                
                // Content Preview
                Text(
                  post.content,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                    height: 1.3,
                  ),
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                ),
                
                const SizedBox(height: 8),
                
                // Tags
                if (post.tags.isNotEmpty) ...[
                  const SizedBox(height: 6),
                  _buildTags(post.tags),
                ],
                
                const SizedBox(height: 8),
                
                // Author Info and Interaction
                _buildPostFooter(post),
              ],
            ),
          ),
        ],
        ),
      ),
    );
  }

  Widget _buildPostImages(CommunityPost post) {
    if (post.images.length == 1) {
      return GestureDetector(
        onTap: () {
          // 点击图片进入详情页
          context.push('/community/${post.id}', extra: post);
        },
        child: ClipRRect(
          borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
          child: AspectRatio(
            aspectRatio: 3 / 4,
            child: Image.network(
              post.images[0],
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  color: Colors.grey[200],
                  child: Icon(
                    Icons.image_not_supported,
                    color: Colors.grey[400],
                    size: 40,
                  ),
                );
              },
            ),
          ),
        ),
      );
    } else {
      return ClipRRect(
        borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
        child: SizedBox(
          height: 200,
          child: PageView.builder(
            itemCount: post.images.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: () {
                  // 点击图片进入详情页
                  context.push('/community/${post.id}', extra: post);
                },
                child: Image.network(
                  post.images[index],
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      color: Colors.grey[200],
                      child: Icon(
                        Icons.image_not_supported,
                        color: Colors.grey[400],
                        size: 40,
                      ),
                    );
                  },
                ),
              );
            },
          ),
        ),
      );
    }
  }

  Widget _buildTags(List<String> tags) {
    return Wrap(
      spacing: 4,
      runSpacing: 4,
      children: tags.take(3).map((tag) {
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
          decoration: BoxDecoration(
            color: Colors.blue[50],
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            '#$tag',
            style: TextStyle(
              fontSize: 10,
              color: Colors.blue[600],
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget _buildPostFooter(CommunityPost post) {
    return Row(
      children: [
        // Author Avatar
        CircleAvatar(
          radius: 12,
          backgroundImage: NetworkImage(post.authorAvatar),
          onBackgroundImageError: (exception, stackTrace) {},
          child: post.authorAvatar.isEmpty
              ? Icon(Icons.person, size: 16, color: Colors.grey[600])
              : null,
        ),
        
        const SizedBox(width: 6),
        
        // Author Name
        Expanded(
          child: Text(
            post.authorName,
            style: const TextStyle(
              fontSize: 11,
              color: Colors.black87,
              fontWeight: FontWeight.w500,
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ),
        
        // Like Button
        GestureDetector(
          onTap: () => _toggleLike(post),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                post.isLiked ? Icons.favorite : Icons.favorite_border,
                size: 16,
                color: post.isLiked ? Colors.red : Colors.grey[600],
              ),
              const SizedBox(width: 2),
              Text(
                '${post.likeCount}',
                style: TextStyle(
                  fontSize: 11,
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  void _showSearchDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('搜索社区'),
        content: TextField(
          controller: _searchController,
          decoration: const InputDecoration(
            hintText: '输入关键词搜索...',
            prefixIcon: Icon(Icons.search),
            border: OutlineInputBorder(),
          ),
          autofocus: true,
          onSubmitted: (value) {
            _onSearch(value);
            Navigator.of(context).pop();
          },
        ),
        actions: [
          TextButton(
            onPressed: () {
              _searchController.clear();
              _onSearch('');
              Navigator.of(context).pop();
            },
            child: const Text('清除'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              _onSearch(_searchController.text);
              Navigator.of(context).pop();
            },
            child: const Text('搜索'),
          ),
        ],
      ),
    );
  }

  Future<void> _onRefresh(CommunityProvider provider) async {
    await provider.loadPosts(refresh: true);
  }
}